package com.efrei.uchat.io;

import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.model.user.Chatter;
import com.efrei.uchat.model.user.Chatters;
import com.efrei.uchat.server.UChatServer;

public class Sessions {

	private Map<Integer, Session> sessions = new HashMap<Integer, Session>();
	private Chatters chatters = new Chatters();
	private UChatServer server;
	
	private int nbSession = 0;
	
	public Sessions(UChatServer server) {
		this.server = server;
	}
	
	/**
	 * notify new connection to server
	 * @param client
	 * @return
	 * @throws UChatException
	 * @throws IOException
	 */
	public void newClient(Socket client) throws UChatException, IOException {
		// create new session with generated id > 0
		// this session will be added after client login
		// see ClientListener.initConnection(msg) and sessionCompleted(session)
		int id = ++nbSession;
		new Session(id, server, client);
	}
	
	/**
	 * called by session after client has succeeded login
	 * @param session
	 * @throws UChatException
	 */
	public void sessionCompleted(Session session) throws UChatException {
		sessions.put(session.getId(), session);
		chatters.addChatter(session.getChatter());
		
		System.out.println("session "+
					session.getId()+
					" for user "+
					session.getChatter().getPseudo()+
					" is completed.");
	}
	
	/**
	 * @param chatter
	 * @return session attached with this chatter or null
	 */
	public Session getSession(Chatter chatter) {
		for (Session session : sessions.values()) {
			if(session.getChatter().equals(chatter)) {
				return session;
			}
		}
		return null;
	}
	
	/**
	 * @param id
	 * @return session or null
	 */
	public Session getSession(int id) {
		return sessions.get(id);
	}
	
	public void removeSession(int id) throws UChatException {
		Session session = sessions.get(id);
		if(session == null) {
			throw new UChatException(
					String.format("session %s not found and can't be removed", id));
		}
		// remove session
		sessions.remove(id);
		// and chatter associated
		chatters.remove(session.getChatter());
	}
	
	public Chatters getChatters() {
		return chatters;
	}
}
